package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.BrandAdapter1;
import com.dotstone.chipism.bean.BrandSort;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.BrandManager;
import com.dotstone.chipism.util.CharacterParser;
import com.dotstone.chipism.util.PinyinComparator;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.ClearEditText;
import com.dotstone.chipism.view.SideBar;
import com.dotstone.chipism.view.SideBar.OnTouchingLetterChangedListener;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.client.IRemoteClient.CallbackOnBrandLoaded;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.remote.entity.Brand;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 
 * @author ise1 选择品牌 然后根据所选择的家电类型 跳转至不同的遥控器界面
 */
public class BrandSelectionActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private TextView mTitleTv;
	private int type;
	private ListView mBrandLv;
	// private BrandAdapter brandAdapter;
	private BrandAdapter1 brandAdapter1;
	private RemoteClient rc;
	private List<Brand> bs = new ArrayList<Brand>();
	private SideBar sideBar;
	private ClearEditText mClearEditText;
	private SVProgressHUD mSVProgressHUD;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<BrandSort> brandSorts = new ArrayList<BrandSort>();

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;

		default:
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				mBrandLv.setAdapter(brandAdapter1);
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_brand_selection;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		mSVProgressHUD = new SVProgressHUD(BrandSelectionActivity.this);
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mTitleTv.setVisibility(View.VISIBLE);
		mBrandLv = $(R.id.brand_lv);
		type = getIntent().getIntExtra("type", 999);
		initBrand(); // 根据传入的家电类型获取品牌列表
		String appliance = Util.getAppliance(getApplicationContext(), type);
		mTitleTv.setText(appliance + "： 品牌 选择");
		boolVersion();
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = brandAdapter1.getPositionForSection(s.charAt(0));
				if (position != -1) {
					mBrandLv.setSelection(position);
				}

			}
		});
		mBackL.setOnClickListener(this);
		mBrandLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
				// TODO Auto-generated method stub
				// Brand b = bs.get(position);
				if (brandAdapter1.getAdapterData().size() < position) {
					ToastShow.Show(getApplicationContext(), "搜索失败，请重新搜索");
					return;
				}
				long brandId = brandAdapter1.getAdapterData().get(position).getBrandId();
				// Brand b = brandAdapter1.getAdapterData().get(position);
				Brand b = getBrandById(brandId);
				Log.i("wmy",
						"点击品牌 = " + b.getBrand_cn() + " " + b.getBrand_en() + " " + b.getBrand_other() + " "
								+ b.getBrand_tw() + " " + b.getId() + " " + b.getPinyin() + " " + b.getPy() + " "
								+ b.getRemarks() + " " + b.getBrandIdAll() + " " + b.getBrandIdOther());
				// 获取所点击的品牌ID
				// 根据所选的家电类型
				// 跳转至型号选择界面
				if (type == DeviceType.DEVICE_TYPE_FAN) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddFanActivity1.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else if (type == DeviceType.DEVICE_TYPE_TV) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddTvActivity1.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else if (type == DeviceType.DEVICE_TYPE_AIR_CONTROLLER) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddAirActivity3.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else if (type == DeviceType.DEVICE_TYPE_BOX) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddBoxActivity1.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else if (type == DeviceType.DEVICE_TYPE_PROJECTOR) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddProjectorActivity1.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else if (type == DeviceType.DEVICE_TYPE_DVD) {
					Intent intent = new Intent(BrandSelectionActivity.this, AddDvdActivity1.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				} else {
					Intent intent = new Intent(BrandSelectionActivity.this, ModelSelectionActivity.class);
					intent.putExtra("type", type);
					intent.putExtra("brandId", b.getId());
					intent.putExtra("brand", b.getBrand_cn());
					startActivity(intent);
				}
			}
		});

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	private void filterData(String filterStr) {
		Log.i("wmy", "过滤字段 = " + filterStr);
		List<BrandSort> filterDateList = new ArrayList<BrandSort>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = brandSorts;
		} else {
			filterDateList.clear();
			for (BrandSort sortModel : brandSorts) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		Log.i("wmy", "filterDateList.size() = " + filterDateList.size());
		brandAdapter1.updateListView(filterDateList);
	}

	private void initBrand() {
		rc = new RemoteClient(getApplicationContext());
		mSVProgressHUD.showWithStatus("正在加载");
		rc.load_brands(new CallbackOnBrandLoaded() {

			@Override
			public void onBrandLoaded(int errcode, List<Brand> brands) {
				// TODO Auto-generated method stub
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				bs = rc.getBrandByType(type, "");
				Log.i("wmy", "270获取品牌数 = " + bs.size());
				for (int i = 0; i < bs.size(); i++) {
					Log.i("wmy", "品牌" + bs.get(i).getBrand_cn());
				}
				for (int i = 0; i < bs.size(); i++) {
					Brand b = bs.get(i);
					BrandSort bsort = new BrandSort();
					bsort.setName(b.getBrand_cn());
					String pinyin = "";
					if (b.getBrand_cn() != null) {
						pinyin = characterParser.getSelling(b.getBrand_cn());
						if (pinyin.length() < 2) {
							bsort.setSortLetters("#");
						} else {
							String sortString = pinyin.substring(0, 1).toUpperCase();
							if (sortString.matches("[A-Z]")) {
								Log.i("wmy", bs.get(i).getBrand_cn() + "[A-Z]");
								bsort.setSortLetters(sortString.toUpperCase());
							} else {
								Log.e("wmy", bs.get(i).getBrand_cn() + "#");
								bsort.setSortLetters("#");
							}
						}
					} else {
						Log.e("wmy", bs.get(i).getBrand_cn() + "#");
						bsort.setSortLetters("#");
					}
					if (b.getBrand_en() != null && b.getBrand_en().length() != 0) {
						bsort.setName_en(b.getBrand_en());
					}else{
						bsort.setName_en(pinyin);
					}
					bsort.setBrandId(b.getId());
					brandSorts.add(bsort);
				}
				Collections.sort(brandSorts, pinyinComparator);
				if (brandSorts.size() == 0 && type == DeviceType.DEVICE_TYPE_AIR_CONTROLLER) {
					brandSorts = BrandManager.getInstance().getBrandSorts();
					brandAdapter1 = new BrandAdapter1(BrandSelectionActivity.this, brandSorts);
					mBrandLv.setAdapter(brandAdapter1);
				} else {
					brandAdapter1 = new BrandAdapter1(BrandSelectionActivity.this, brandSorts);
					mBrandLv.setAdapter(brandAdapter1);
				}
			}
		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private Brand getBrandById(long id) {
		for (Brand b : bs) {
			if (b.getId() == id) {
				return b;
			}
		}
		return null;
	}

}
